// PALib Template Application

// Includes
#include <PA9.h>       // Include for PA_Lib
#include "Squared.h"
#include "Chain.h"
//#include "gfx/all_gfx.h"
#include "gfx/all_gfx.c"



void wait()
{
	for (int i=0;i<30;i++)
	{
		PA_WaitForVBL();
	}
	return;
}
int max(int a, int b)
{
	return a-b ? a : b;
}
int min(int a, int b)
{
	return b-a ? a : b;
}


bool isBetween(int x0, int y0, int x1, int y1, int x2, int y2)
{
	if((x0>min(x1,x2))&&(x0<max(x1,x2))&&(y0>min(y1,y2))&&(y0<max(y1,y2)))
	{
		float m = (y2-y1)/(x2-x1);
		float q = y1 - (m * x1);

		if ((float)y0 == ((m * x0) + q))
			return true;
		else
			return false;
	}
	else
		return false;

}




int main()
{
	PA_Init();    // Initializes PA_Lib
	PA_InitVBL(); // Initializes a standard VBL
	PA_InitText(1, 2);
	/*PA_InitText(0, 2);
	PA_InitText(1, 2);
	PA_OutputSimpleText(1, 1, 2, "Hello World!");
	PA_WaitForVBL();
	PA_OutputSimpleText(0, 1, 2, "Hello Devs..");*/
	
	Squared s, t, z;

	s.X = PA_RandMax(10);//2;
	s.Y = PA_RandMax(10);//4;

	s.SpeedX = PA_RandMax(10);//5;
	s.SpeedY = PA_RandMax(10);//0;
	
	t.X = PA_RandMax(10);//7;
	t.Y = PA_RandMax(10);//6;

	t.SpeedX = PA_RandMax(10);//1;
	t.SpeedY = PA_RandMax(10);//3;

	z.X = PA_RandMax(10);//5;
	z.Y = PA_RandMax(10);//5;

	z.SpeedX = PA_RandMax(10);//4;
	z.SpeedY = PA_RandMax(10);//2;


	int current_level = 3;

	Chain c;
	c.AddSqr(s);
	c.AddSqr(t);
	c.AddSqr(z);

	for(int i=0;i<10;i++)
	{
		Squared a;
		a.X = PA_RandMax(10);
		a.Y = PA_RandMax(10);
		a.SpeedX = PA_RandMax(10);
		a.SpeedY = PA_RandMax(10);
	}


	for(int i=0;i<c.size;i++)
	{
		PA_LoadSpritePal(0, // Screen
			i, // Palette number
			(void*)sprt_Pal);	// Palette name
					
		PA_CreateSprite(0, // Screen
			i, // Sprite number
			(void*)sprt_Sprite, // Sprite name
			OBJ_SIZE_8X8, // Sprite size
			1, // 256 color mode
			i, // Sprite palette number
			c.X(i), c.Y(i)); // X and Y position on the screen
	}

	
	PA_Init8bitBg(1, 1);
	


	// Infinite loop to keep the program running
	while (1)
	{
		
		for(int i=0;i<c.size;i++)
		{
			

			if (c.isDone(i))
			{
				if (i>0)
					PA_Draw8bitLineEx(0, c.X(i),c.Y(i),c.X(i-1),c.Y(i-1), 8, 2);
				PA_MoveSprite(i);
			}
			else
			{
				c.MoveStep(i);
				PA_SetSpriteXY(0, i, c.X(i), c.Y(i));

				for(int j=0;j<(i-1);j++)
				{
					if (isBetween(c.X(i),c.Y(i),c.X(j),c.Y(j),c.X(j+1),c.Y(j+1)))
					{
						PA_OutputText(1, 1, 2, "Sprite %d collided!", i);
						return 1;
					}
				}
				if (PA_SpriteTouched(i))
				{
					PA_OutputText(1, 1, 2, "Sprite %d stopped", i);
					c.Stop(i);
				}
			}


		}

		
		/*PA_OutputText(1,0,0,"you chose: %d", s.X);//
		PA_OutputText(0,0,0,"you chose: %d", s.Y);//*/
		wait();
	}
	
	return 0;
}
